<!--  
 * 项目管理 - 右侧抽屉新增编辑内容
 * @author: 张锋
 * @since: 2025-02-10
 * index.vue
-->
<template>
  <div class="offsideDrawer">
    <el-drawer v-model="isShowDrawer" title="" :before-close="closedDrawer">
      <template #title>
        <div class="drawer-title">
          <div class="title-icon"></div>
          <div class="title-text">
            <span>项目名称：{{ props.data.projectName }}</span>
          </div>
        </div>
      </template>
      <template #default>
        <el-form class="drawer-content" :model="form" :rules="rules" ref="validateform">
          <el-form-item label="总价：" prop="totalPrice" class="projectsname">
            <el-input v-model="form.totalPrice" type="number" placeholder="请输入项目总价" />
          </el-form-item>
          <el-form-item label="含税价格：" prop="includTaxPrice">
            <el-input v-model="form.includTaxPrice" type="number" placeholder="请输入含税价格"  />
          </el-form-item>
          <el-form-item label="未税价：" prop="untaxedPrice">
            <el-input v-model="form.untaxedPrice" type="number" placeholder="请输入未税价格"  />
          </el-form-item>
          <el-form-item label="税金：" prop="taxPrice">
            <el-input v-model="form.taxPrice" placeholder="请输入项目税金"></el-input>
          </el-form-item>
          <el-form-item v-if="props.ProjectsId" label="投标附件">
            <ul>
              <li v-for="(item,index) in data.fileArray" :key="item">
                <a :href="item">投标附件{{ index + 1 }}</a>
              </li>
            </ul>
          </el-form-item>
          <el-form-item v-if="props.ProjectsId" label="上传投标附件">
            <el-upload :multiple="false" :file-list="state.fileList" class="upload-demo" 
            drag :http-request="uploadHttpRequest" :show-file-list="true" :before-upload="checkFile"
            :on-remove="removeFile">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖拽至此 /
                <em>点击上传</em>
              </div>
            </el-upload>
            <a :href="form.fileArray">{{ form.fileArray }}</a>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" size="mini" style="width: 100px" @click="save">提交</el-button>
          <el-button size="mini" style="width: 100px" @click="closedDrawer">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, defineProps, defineEmits, onMounted, watch, inject } from 'vue'
import { getAllMenuList, addToubiao, editToubiao, getToubiaoInfo } from '@/api/interface/Tendering.js'
import { getUserListApi } from '@/api/interface/userManage.js'
import { uploadFilePathApi, dowloadOtherFileApi } from '@/api/public/uploadFile.js'

import { successHandle, recursiveId } from '@/utils/common.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const store = useStore()
const router = useRouter()
const props = defineProps({
  isShowDrawer: {
    //是否展开项目抽屉
    type: Boolean,
    default: false,
  },
  isEditToubiao: {
    //是否展开项目抽屉
    type: Boolean,
    default: false,
  },
  ProjectsId: [String],
  id: {
    //是否展开项目抽屉
    type: String,
    default: false,
  },
  data: {
    //row数据
    type: Object,
    default: () => {},
  },
})

const emits = defineEmits(['close', 'refresh'])
const reload = inject('reload')
const state = reactive({
  allMenuList: [], //所有菜单数据
  selectAllIdList: [], //选中的所有menuIdList
  userList: [],
  fileList: [],
  choosedFileList: [],

})
const drawer = reactive({
  title: '新增',
})
//新增编辑 form
let form = reactive({
  id: '',
  projectId: "",
  fileArray: '',
  totalPrice: '', //总价
  taxPrice: '', //税金
  includTaxPrice: '', //含税价格
  untaxedPrice: '', //未税价格
})

onMounted(() => {
})

watch(
  () => props.isShowDrawer,
  (val) => {
    if (props.isEditToubiao) {
      getInfo()
    }
  }
)

//表单验证
const rules = {
  totalPrice: [{ required: true, message: '必填项', trigger: 'blur' }],
  taxPrice: [{ required: true, message: '必填项', trigger: 'blur' }],
  includTaxPrice: [{ required: true, message: '必填项', trigger: 'blur' }],
  untaxedPrice: [{ required: true, message: '必填项', trigger: 'blur' }],
}
//获取注册用户列表

//表单元素
const validateform = ref(null)

//树 dom
const tree = ref(null)

const getInfo = () => {
  if(!props.ProjectsId){
    return
  }
  getToubiaoInfo({ projectId: props.ProjectsId }).then( res => {
    let data = res.data[0]
    form.totalPrice = data.totalPrice
    form.taxPrice = data.taxPrice
    form.includTaxPrice = data.includTaxPrice
    form.untaxedPrice = data.untaxedPrice
    form.projectId = data.projectId
    form.id = data.id
    form.fileArray = data.fileArray
  })
}

//关闭抽屉 清空数据
const closedDrawer = () => {
  validateform.value.resetFields()
  emits('close')
  tree.value.getCheckedNodes().some((item) => {
    tree.value.setChecked(item.id, false, true)
  })
  for (let key in form) {
    form[key] = ''
  }
  drawer.title = '新增'
}
//新增项目调用接口
const postaddRole = (data) => {
  addToubiao(data).then((res) => {
    successHandle(res)
    closedDrawer()
    emits('refresh')
    emits('close')
  })
}

//修改项目调用接口
const puteditRole = (params) => {
  editToubiao(params).then(async (res) => {
    successHandle(res)
    closedDrawer()
    emits('refresh')
    if (res.status === 200) {
      reload()
      await store.dispatch('user/getMenuList')
      await store.dispatch('routes/setAllRoutes').then((res) => {
        res.forEach((item) => {
          router.addRoute(item)
        })
      })

      emits('refresh')
      emits('close')
    }
  })
}

//上传文件
const uploadHttpRequest = (data) => {
  let fd = new FormData()
  fd.append('file', data.file)
  console.log("data.file",data.file);
  uploadFilePathApi(fd).then((res) => {
    state.choosedFileList.push( res.data )
    ElMessage.success('上传成功！')
  })
}

//选择文件
const checkFile = (data) => {
  let index = data.name.lastIndexOf('.')
  let type = data.name.slice(index + 1)
  if (type == 'doc' || type == 'docx' || type == 'xlsx') {
    return true
  }else{
    ElMessage.error('不是合法的文件格式')
    return false;
  }
}
//删除文件
const removeFile = (file, files) => {
  state.choosedFileList = state.choosedFileList.filter(item => item.name !== file.name);
}

//保存
const save = () => {
  validateform.value.validate((valid) => {
    if (valid) {
      state.userList.map((item) => {
        if (item.userName == form.projectOperId) {
          form.projectOperName = item.realName
        }
      })
      if (props.isEditToubiao) {

        form.fileArray = state.choosedFileList[0]
        //修改
        console.log('修改')
        const params = {
          ...form,
        }
        puteditRole(params)
      } else {
        //新增
        form.fileArray = state.choosedFileList[0]
        form.projectId  = props.ProjectsId
        const params = {
          ...form,
        }
        postaddRole(params)
      }
    } else {
      console.log('没通过验证')
    }
  })
}


</script>
<style lang="scss" scoped>
.el-form-item__content {
  width: 100%;
}

.projectsname {
  margin-bottom: 0;

  :deep(.el-form-item__error) {
    top: 90%;
  }
}
</style>
